from textual.app import App, ComposeResult, ScreenStackError
from textual.containers import Horizontal, Vertical
from textual.binding import Binding
from textual.widgets import Footer, LoadingIndicator

from screens.main_option import Options
from screens.help import HelpScreen
from mywidgets.users import Users
from mywidgets.clock import Clock
from mywidgets.cpubar import CpuBox
from mywidgets.mydirectorytree import MyDirectoryTree
from mywidgets.mytable import MyDataTable

from datetime import datetime
from rich.console import Console
import psutil
import os
import sys

"""
软件要求：

python >= 3.10
textual >= 0.35.0
psutil >= 5.9.5
rich >= 13.3.5
nest-asyncio >= 1.5.7

软件设计：主页面为Tab界面，可切换不同模块：文件管理、CPU/内存占用率、进程管理、用户管理。
"""

class App(App):
    CSS_PATH = "main.css"
    BINDINGS = [
        Binding(key="ctrl+c", action="quit", description="终止软件"),
        Binding(key="q", action="on_q_pressed", description="退出"),
        # Binding(key="o", action="on_o_pressed", description="设置"),
        Binding(key="h", action="on_h_pressed", description="帮助"),
    ]

    def __init__(self):
        super().__init__()
            
    def action_on_o_pressed(self):
        if self.screen.id=="_default":  # 初始界面id，此时界面栈中元素为0个
            self.push_screen("Option")  # 第一次需要将设置界面压入栈中
        elif self.screen.id=="Option":
            self.pop_screen()
        else:                           # 按O切换至设置界面
            self.switch_screen("Option")

    def action_on_h_pressed(self):
        if self.screen.id=="_default":  # 初始界面id，此时界面栈中元素为0个
            self.push_screen("Help")    # 第一次需要将设置界面压入栈中
        elif self.screen.id=="Help":
            self.pop_screen()
        else:                           # 按h切换至设置界面
            self.switch_screen("Help")
    
    def action_on_q_pressed(self):
        try:
            self.pop_screen()
        except ScreenStackError:
            self.exit()

    def on_mount(self):
        self.update_disk_label()
        self.query_one("#tree_box").border_subtitle = "鼠标/Enter打开文件"
        self.query_one("#cpubox").border_title = "Cpu与内存状态池"
        self.query_one("#cpubox").border_subtitle = "Tab切换各组件"
        self.query_one("#four_container").border_title = "时钟"
        self.query_one("#user_table").border_title = "在线用户"
        self.query_one("#user_table").border_subtitle = "鼠标右键/Space踢出选中用户"
        self.query_one("#pid_table").border_title = "进程列表"
        self.query_one("#pid_table").border_subtitle = "鼠标右键/Space终止选中进程"
        # 先聚焦第一个控件
        self.query_one("#tree_box").has_focus=True
        self.query_one("#tree_box").styles.border = ("solid", "orangered")
        

    def on_ready(self) -> None:
        self.update_clock()
        self.set_interval(1, self.update_clock)

    def update_clock(self) -> None:
        clock = datetime.now().time()
        try:
            self.query_one("#clock").update(f"{clock:%T}")
        except:
            pass
    
    def get_data_unit(self, data):
        a = data/1024
        b = a/1024
        c = b/1024
        if round(c) != 0:
            data_ = round(c, 2)
            unit = 'GB'
        elif round(b) != 0:
            data_ = round(b, 2)
            unit = 'MB'
        elif round(a) != 0:
            data_ = round(a, 2)
            unit = 'KB'
        return data_, unit

    def update_disk_label(self):
        disk_info = psutil.disk_usage("/")  # 根目录磁盘信息
        disk_total = disk_info.total
        disk_total, disk_total_unit = self.get_data_unit(disk_total)
        disk_percent = disk_info.percent
        disk_label = "共"+str(disk_total)+disk_total_unit+",使用"+str(disk_percent)+"%"
        self.query_one("#tree_box").border_title = "磁盘/"+disk_label

    def compose(self) -> ComposeResult:
        # 安装设置屏幕
        self.install_screen(Options(id="Option"), name="Option")
        self.install_screen(HelpScreen(id="Help"), name="Help")
        # 读取目录
        # 初始化当前目录的路径
        current_path = os.getcwd()
        env = os.name
        if env == 'nt':
            # Windows系统
            path_dir = current_path.split('\\')
        elif env == 'posix':
            # Linux 或 Mac 系统
            path_dir = current_path.split('/')
            path_dir[0] = '/'
        yield Footer()
        yield Vertical(Vertical(MyDirectoryTree(path_dir[0], id="tree_view"),id="tree_box"),id="one",)
        # 实例化
        self.cpu_box = CpuBox()
        yield Vertical(LoadingIndicator(),Horizontal(self.cpu_box), id="two", )
        yield Vertical(Clock(),id="four",)
        yield Vertical(Users(id="user_table"),id="five")
        yield Vertical(MyDataTable(id="pid_table"),id="three",)

if __name__ == "__main__":
    app = App()
    if os.geteuid() != 0:
        console = Console()
        console.print("[red]抱歉，此应用只允许管理员使用。您为普通用户，没有使用该应用的权限！")
        sys.exit(1)
    else:
        app.run()
    
        

    
